<?php
/**
 * @version		1.6
 * @package		TwitterTweet K2 Plugin (K2 plugin)
 * @author    Daniel Eliasson Stilero AB - http://www.stilero.com
 * @copyright	Copyright (c) 2011 Stilero AB. All rights reserved.
 * @license	GPLv2
* 	Joomla! is free software. This version may have been modified pursuant
* 	to the GNU General Public License, and as distributed it includes or
* 	is derivative of works licensed under the GNU General Public License or
* 	other free or open source software licenses.
 *
 *  This file is part of K2 TwitterTweet.

    K2 TwitterTweet is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BlogPing Pro is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with K2 TwitterTweet.  If not, see <http://www.gnu.org/licenses/>.
*/

// no direct access
defined('_JEXEC') or die ('Restricted access');

/**
 * Example K2 Plugin to render YouTube URLs entered in backend K2 forms to video players in the frontend.
 */

// Load the K2 Plugin API
JLoader::register('K2Plugin', JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'k2plugin.php');

class plgK2Twittertweet extends K2Plugin {
	var $pluginName = 'twittertweet';
	var $pluginNameHumanReadable = 'TwitterTweet K2 Plugin';
	var $pluginParams;
	var $k2Item;
	var $config;
        var $twitterFormToken;
        var $fullTweet;
        var $inBackend;
        var $errorOccured;
        const HTTP_STATUS_FOUND = '302';
        const HTTP_STATUS_OK = '200';

	function plgK2Twittertweet( & $subject, $params) {
		parent::__construct($subject, $params);
		$this->loadLanguage();
                $this->errorOccured = FALSE;
                $config = array(
                    'twitterLoginFormURL'   =>      'https://mobile.twitter.com/session/new',
                    'twitterLoginPostURL'   =>      'https://mobile.twitter.com/session',
                    'twitterDataURL'        =>      'https://mobile.twitter.com/',
                    'twitterUsername'       =>      $this->params->def('username'),
                    'twitterPassword'       =>      $this->params->def('password'),
                    'twitterWebAgent'       =>      'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
                    'twitterMaxHashTags'    =>      3,
                    'tinyURLAPI'            =>      'http://tinyurl.com/api-create.php?url=',
                    'curlPost'              =>      1,
                    'curlSSLVerifyPeer'     =>      false,
                    'curlSSLVerifyHost'     =>      2,
                    'curlCookieFile'        =>      '',
                    'curlReturnTransfer'    =>      1,
                    'curlFollowLocation'    =>      0
                );
	}

	function onK2AfterDisplayContent( & $item, & $params, $limitstart) {
		$mainframe = &JFactory::getApplication();
		// Get the K2 plugin params (the stuff you see when you edit the plugin in the plugin manager)
		$plugin = & JPluginHelper::getPlugin('k2', 'twittertweet');
		$this->pluginParams = new JParameter($plugin->params);
		// Get the output of the K2 plugin fields (the data entered by your site maintainers)
		if(K2_JVERSION == '15') {
                    $plugins = new K2Parameter($item->plugins, '', $this->pluginName);
		}
		else {
                    $plugins = new JParameter($item->plugins, '', $this->pluginName);
		}
		//Begin the posting
                $this->inBackend = false;
		$this->setK2Item($item);
		$this->tweet();
		return;
        }
	
	function onAfterK2Save( &$item, $isNew ) {
		$mainframe = &JFactory::getApplication();
		// Get the K2 plugin params (the stuff you see when you edit the plugin in the plugin manager)
		$plugin = & JPluginHelper::getPlugin('k2', 'twittertweet');
		$this->pluginParams = new JParameter($plugin->params);
		// Get the output of the K2 plugin fields (the data entered by your site maintainers)
		if(K2_JVERSION == '15') {
                    $plugins = new K2Parameter($item->plugins, '', $this->pluginName);
		}
		else {
                    $plugins = new JParameter($item->plugins, '', $this->pluginName);
		}
                $this->inBackend = true;
		$this->prepareTables();
		$this->setK2Item($item);
		$this->tweet();
		return;
	}

	/**
	 * This method takes care of initiating the posting.
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param integer	$itemid		K2 item ID
	 * @param string	$option		Joomla component option
	 * @param array 	$tags	An array with tags
	 *
	 * @return none
	 */
	function _initiatePosting($item, $option="com_article", $tags="")
	{
		//Check if we are ready to ping, and begin.
		if($this->_checkBeforeTweet($item)){
			//Explode the meta to an array
			if( ($this->params->def('metahash')) ){
				$hashtags = (count($tags) > 0)? $this->_getHashTags($tags):$this->_getHashTags($item->tags);
			}

			//Compose the full URL based on what component we've used
			$fullURL = $this->_getUrl($item->id, $option);
			$shortUrl = $this->_makeShortURL($fullURL);
			$fullTextMessage = $this->_getMessage($item->title, $option);
			$truncatedTextMessage = substr($fullTextMessage, 0, 140 - count($shortUrl) -1 - count($hashtags) -1);
			$twittermessage = $truncatedTextMessage." ".$shortUrl.$hashtags;

			if($this->_updateTwitterStatus($twittermessage)){
				$this->_saveTweeted($item);
				$this->_displayMessage("Tweeted: ".$twittermessage);
				return true;
			}
		}
		return false;
	}

	/**
	 * This method returns a three hashtags.
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param object	$tags	Tags array
	 *
	 * @return string	hashtags
	 */
	function _getHashTags($tags)
	{
		$tagarr;
		$i = 0;


		//Check if tags exists, otherwise return
		if(count($tags) == 0){
			return;
		}

		foreach ($tags as $key => $value) {
			if($i++ < 3){
				$tagarr[]= str_replace(" ", "", $value->name) ;
			}
		}

		$tagarr = ( count($tagarr) > 0 )? implode(",",$tagarr):"";
		//Remove any blank spaces
		$metakeys = str_replace(" ", "", $tagarr);
		$hashtags = explode(",", $metakeys);

		$implodedtags = ( count($hashtags) >0 )? implode(" #", $hashtags):"";
		$hashtags = (count($hashtags) >0)?" #".$implodedtags:"";

		return $hashtags;
	}

	/**
	 * Get Tags from the database
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param object	&$article	content object.
	 *
	 * @return Array	an array with the hashtags found
	 */
	function _loadTags($article){

		//Variables used for changes since 1.5
		$sectionCat;	//Used for sections (1.5) or categories (1.6+)
		$query;			//Used since joomla 1.6+ handles queries different from 1.5

		// Get a database object
		$db		= &JFactory::getDbo();

		/**
		 * WORKING SQL
		 *
		 * SELECT name FROM `jos_k2_tags`
		 * INNER JOIN `jos_k2_tags_xref`
		 * ON `jos_k2_tags_xref`.tagID = `jos_k2_tags`.id
		 * WHERE `jos_k2_tags_xref`.itemID = '3'
		 */

		if(version_compare(JVERSION,'1.7.0','ge')) {
			//the article has tags
			$query	= $db->getQuery(true);

			$query->select('name');
			$query->from('#__k2_tags AS t');
			$query->innerJoin('#__k2_tags_xref AS x ON x.tagID = t.id');
			$query->where('x.itemID = '.(int) $article->id);

		} elseif(version_compare(JVERSION,'1.6.0','ge')) {
			//the article has tags
			$query	= $db->getQuery(true);

			$query->select('name');
			$query->from('#__k2_tags AS t');
			$query->innerJoin('#__k2_tags_xref AS x ON x.tagID = t.id');
			$query->where('x.itemID = '.(int) $article->id);
		}  elseif(version_compare(JVERSION,'1.5.0','ge')) {

			$query = "SELECT ".$db->nameQuote('name').
						" FROM ".$db->nameQuote('#__k2_tags')." AS t".
						" INNER JOIN " . $db->nameQuote('#__k2_tags_xref')." AS x".
						" ON  x.tagID = t.id".
						" WHERE x.itemID = " . $db->Quote($article->id);
		}
		$db->setQuery($query);
		$result = $db->loadObjectList();
		return $result;
	}

	/**
	 * This method takes a url and returns a shortened version.
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param string	$URLToConvert	The URL to shorten
	 *
	 * @return string	shorter Url
	 */
	function _makeShortURL($URLToConvert) {

    	$shortURL= @file_get_contents("http://tinyurl.com/api-create.php?url=" . $URLToConvert);

		//We failed to get the URL, try using cURL instead
		if($shortURL == ""){
			$shortURL = $this->_getTinyUrlUsinCurl($URLToConvert);
		}

		//Check if the URL to Convert is longer than the tinyurl
		if( (strlen($URLToConvert) < strlen($shortURL)) || $shortURL == "" ){
			$shortURL = $URLToConvert;
		}
     	return $shortURL;
	}
	/**
	 * This method takes a url and returns a shortened version using cURL.
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param string	$URLToConvert	The URL to shorten
	 *
	 * @return string	shorter Url
	 */
	function _getTinyUrlUsinCurl($URLToConvert) {


    	$data_url = "http://tinyurl.com/api-create.php?url=" . $URLToConvert;

		$postvars = array('url' => $URLToConvert );

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$data_url); 	 //The auth page to visit
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postvars)); //Build a query from the postarray
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$the_results = curl_exec ($ch);							//Go get the page and put the result in a variable
		$resultArray = curl_getinfo($ch);
		curl_close ($ch);	//Close the connection for now

		//Show the proper message
		switch ($resultArray['http_code']) {
			case '200':
				return $the_results;
				break;
			case '302':
				//This is the result when all went well
				return $the_results;
				break;
			default:
				$this->_displayMessage(JText::_("Errorcode:").$resultArray['http_code'], 'error');
				break;
		}
		return false;

	}
	/**
	 * This method returns a Joomla url based on article and id.
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param object	&$article	content object.
	 *
	 * @return string	article url
	 *
	 * DEPRECATED METHOD
	 */
	function _createUrl($article)
	{

				$link = $article->link;


				//Make host url without the ending slash
				$hosturl = substr(JURI::root(), 0, strlen(JURI::root())-1 );
				//Make sure the host is not in the current link, since well add it later.
				//This is required for some SEF-plugins that add the host.
				$link = str_replace($hosturl, "", $link);
				//Add the hosturl again
				$link = $hosturl.$link;

				//Decode the url to work universally
				$link = htmlentities($link);


		return $link;
	}
	/**
	 * This method returns a Joomla url based on article and id.
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param object	&$article	content object.
	 *
	 * @return string	article url
	 */
	function _getUrl($itemid, $option="com_content")
	{
		switch ($option) {
			case 'com_content':
				$parameters = "?option=com_content&view=article&id=".$itemid;
				break;
			case 'com_k2':
				$parameters = "?option=com_k2&view=item&id=".$itemid;
				break;
			case 'com_zoo':
				$parameters = "?option=com_zoo&task=item&item_id=".$itemid;
				break;
			case 'com_virtuemart':
				$parameters = "?option=com_virtuemart&page=shop.product_details&flypage=flypage.tpl&product_id=".$itemid;
				break;
			default:
				//Regular joomla
				$parameters = "";
				break;
		}

		$link = JURI::root()."index.php".$parameters;

		return $link;
	}

	/**
	 * This method returns a Messagetext based on the type of component we're using.
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param string	$itemtitle 		title for the item
	 * @param string	$option 		type of component
	 * 	 *
	 * @return string	article url
	 */
	function _getMessage($itemtitle, $option="com_content")
	{
		switch ($option) {
			case 'com_virtuemart':
				$message = JText::_("PLG_CONTENT_K2_TWITTERTWEET_VM_MESSAGE").$itemtitle;
				break;
			default:
				//Regular joomla
				$message = $itemtitle;
				break;
		}

		return $message;
	}

	private function setTwitterLoginFormToken() {
            $twitterLoginFormPage = $this->getTwitterLoginFormPage();
            $arrayWithTheTokenInTheMiddle = explode("authenticity_token\" type=\"hidden\" value=\"", $twitterLoginFormPage);
            $arrayWithTheTokenInTheBeginning = explode("\"", $arrayWithTheTokenInTheMiddle[1]);
            $twitterLoginFormToken = $arrayWithTheTokenInTheBeginning[0];
            $this->twitterFormToken = $twitterLoginFormToken;
	}

        private function serverSupportsRequiredFunctions(){
            if( !function_exists( curl_init ) ){
                $this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NO_CURL_SUPPORT'), 'error');
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isLoginDetailsEntered() {
            $twitterusername = $this->params->def('username');
            $twitterpassword = $this->params->def('password');
            if( $twitterusername == "" || $twitterpassword == ""){
                $this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOLOGINDETAILS'), 'error');
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isItemActive() {
            if (($this->k2Item->published != 1)){
                $this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOTACTIVE'));
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isItemPublished() {
            $date =& JFactory::getDate();
            $currentDate = $date->toMySQL();
            $itemPublishDate = $this->k2Item->pubplish_up;
            if ( $itemPublishDate > $currentDate ){
                $this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOTACTIVE'));
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isItemNewEnough() {
            $postItemsNewerThanDate = $this->params->def('items_newer_than');
            $itemPublishDate = $this->k2Item->pubplish_up;
            if( ( $itemPublishDate < $postItemsNewerThanDate) && $postItemsNewerThanDate !="" ){
                $this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_ITEM_OLD'));
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isJoomla15() {
            if(version_compare(JVERSION,'1.5.0','ge')) {
                return TRUE;
            }
            return FALSE;
        }

        private function isJoomla16() {
            if(version_compare(JVERSION,'1.6.0','ge')) {
                return TRUE;
            }
            return FALSE;
        }

        private function isJoomla17() {
            if(version_compare(JVERSION,'1.7.0','ge')) {
                return TRUE;
            }
            return FALSE;
        }
        private function isItemPublic() {
            $publicAccessCode = ($this->isJoomla15())?0:1;
            if( $this->k2Item->access != $publicAccessCode ){
                $this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_RESTRICT'));
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isCategToTweet() {
            $categToPostArray = explode(",", $this->params->def('section_id'));
            $numberOfCategToPost = count($categToPostArray);
            $itemCategID = $this->k2Item->catid;
            if ( $numberOfCategToPost == 0 ){
                return TRUE;
            }
            if ( !in_array( $itemCategID, $categToPostArray ) ){
                $this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOTSECTION'));
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isCookeFileSet() {
            if($this->config['curlCookieFile']){
                return TRUE;
            }else{
                $this->errorOccured = TRUE;
                return FALSE;
            }
        }

        private function isTweetingToEarly(){
		$delayInMinutes = ( !is_numeric($this->params->def('delay')) || $this->params->def('delay')<2 )?3:$this->params->def('delay');
		$currentDate=date("Y-m-d H:i:s");
                $query;
		$db		= &JFactory::getDbo();
		if( $this->isJoomla16() || $this->isJoomla17() ) {
                    $query	= $db->getQuery(true);
                    $query->select('id');
                    $query->from('#__k2_twittertweet_tweeted');
                    $query->where("date > SUBTIME('".$currentDate."','0 0:".$delayInMinutes.":0.0')");
		}  elseif($this->isJoomla15()) {
                    $query = "SELECT "
                        .$db->nameQuote('id').
                        " FROM ".$db->nameQuote('#__k2_twittertweet_tweeted').
                        " WHERE date > SUBTIME('".$currentDate."','0 0:".$delayInMinutes.":0.0')";
		}
		$db->setQuery($query);
		$postMadeWithinDelayTime = $db->loadObject();
		if($postMadeWithinDelayTime){
                    $this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_DELAYED"));
                    $this->errorOccured = TRUE;
                    return TRUE;
		}
		return FALSE;
	}

        private function isItemAlreadyTweeted(){
            $query;
            $db		= &JFactory::getDbo();
            $k2itemID = $this->k2Item->id;
            if($this->isJoomla16() || $this->isJoomla17()) {
                $query	= $db->getQuery(true);
                $query->select('id');
                $query->from('#__k2_twittertweet_tweeted');
                $query->where('article_id=' . $db->Quote($k2itemID));
            }  elseif($this->isJoomla15() ) {
                $sectionCat = $article->sectionid;
                $query = 'SELECT '
                .$db->nameQuote('id').
                    ' FROM '.$db->nameQuote('#__k2_twittertweet_tweeted').
                    ' WHERE '.$db->nameQuote('article_id').'='.$db->Quote($k2itemID);
            }
            $db->setQuery($query);
            $itemAlreadyPosted = $db->loadObject();
            if($itemAlreadyPosted){
                $this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_ALREADY_TWEETED"));
                $this->errorOccured = TRUE;
                return TRUE;
            }
            return FALSE;
	}

        private function prepareToTweet() {
            $this->serverSupportsRequiredFunctions();
            $this->createCookieFile();
            $this->isLoginDetailsEntered();
            $this->isItemActive();
            $this->isItemPublished();
            $this->isItemNewEnough();
            $this->isItemPublic();
            $this->isCategToTweet();
            $this->isTweetingToEarly();
            $this->isItemAlreadyTweeted();
        }

        private function isReadyToTweet() {
            if($this->errorOccured){
                return FALSE;
            }else{
                return TRUE;
            }
        }

        /**
	 * Method makes some initial checks to see if this is an article to ping for.
	 * @param	object	&$article	The article object.  Note $article->text is also available
	 *
	 * @return	boolean
	 * @since	1.6
	 */
	function _checkBeforeTweet($article)
	{
		$publicAccess;


		if(version_compare(JVERSION,'1.7.0','ge')) {
			$publicAccess = 1;
		} elseif(version_compare(JVERSION,'1.6.0','ge')) {
			$publicAccess = 1;
		} elseif(version_compare(JVERSION,'1.5.0','ge')) {
			$publicAccess = 0;
		}

		//Check if the necessary curl library exists
		if( !function_exists(curl_init) ){
			$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NO_CURL_SUPPORT'), 'error');
			return FALSE;
		}
		// Get plugin parameters set by the user
		$twitterusername = $this->params->def('username');
		$twitterpassword = $this->params->def('password');
		$metahash = $this->params->def('metahash');
		$pingsection = $this->params->def('section_id');
		$pingsectionarray = explode(",", $this->params->def('section_id'));
		$pingnew = $this->params->def('pingnew');
		$items_newer_than = $this->params->def('items_newer_than');
		//First check the following:
		// * Do we have a serverlist ready?
		// * is this a section to ping?
		// * is this article active?
		// * is this article published?
		// * is this article public ?
		// If not, return and end this ping session.

		//Check if logindetails are specified
		if( $twitterusername == "" || $twitterpassword == ""){
			$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOLOGINDETAILS'), 'error');
			return FALSE;
		}


		//Article active?
		if (($article->published!=1)){
			$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOTACTIVE'));
			return FALSE;
		}

		//Article published?
		$currentDate = $date =& JFactory::getDate();
		//If the article should be published in the future, then we wont ping
		if ( $article->publish_up > $date->toMySQL() ){
			$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOTACTIVE'));
			return FALSE;
		}

		//Article older than the settings allows?
		if( ( $article->publish_up <  $items_newer_than) && $items_newer_than !="" ){
			$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_ITEM_OLD'));
			return FALSE;
		}

		//Is the article only for registred users?
		if( $article->access != $publicAccess ){
			$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_RESTRICT'));
			return FALSE;
		}


		//Section to ping?
		if ( $pingsection != "" ){
			//The sectionlist is not empty, so we must check which categories to ping

			if ( !in_array($article->catid, $pingsectionarray) ){
				$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOTSECTION'));
				return FALSE;
			}
		}

		/*
		 * DEPRECATED
		// Next check if this article is new, and if ping should be made only on new articles
		if ( ( $pingnew == 1 ) && ( $article->version != 1 ) ){
			//JFactory::getApplication()->enqueueMessage(JText::_('NOTNEW'));
			$this->_displayMessage(JText::_('PLG_CONTENT_K2_TWITTERTWEET_NOTNEW'));
			return FALSE;
		}
		*/
            //Check if its to early to tweet
	        if($this->_tweetShouldBeDelayed($article)){
                     return FALSE;
	        }

		//Finally check if the article is already pinged
		$isArticlePinged = $this->_checkArticleTweeted($article);

		//Now inverse and return
		return !$isArticlePinged;
	}


	/**
	 * This method checks if an article is already tweeted and returns true or false
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param object	&$article	content object.
	 *
	 * @return boolean	pinged
	 */
	function _checkArticleTweeted($article){

		//Variables used for changes since 1.5
		$sectionCat;	//Used for sections (1.5) or categories (1.6+)
		$query;			//Used since joomla 1.6+ handles queries different from 1.5

		// Get a database object
		$db		= &JFactory::getDbo();

		if(version_compare(JVERSION,'1.7.0','ge')) {
			//Check if the current link has already been pinged
			$query	= $db->getQuery(true);
			$query->select('id');
			$query->from('#__k2_twittertweet_tweeted');
			//$query->where('itemlink='.$db->Quote($this->_createUrl($article)));
			$query->where('article_id=' . $db->Quote($article->id));

		} elseif(version_compare(JVERSION,'1.6.0','ge')) {
			//Check if the current link has already been pinged
			$query	= $db->getQuery(true);
			$query->select('id');
			$query->from('#__k2_twittertweet_tweeted');
			//$query->where('itemlink='.$db->Quote($this->_createUrl($article)));
			$query->where('article_id=' . $db->Quote($article->id));

		}  elseif(version_compare(JVERSION,'1.5.0','ge')) {
			$sectionCat = $article->sectionid;
			$query = 'SELECT '
						.$db->nameQuote('id').
						' FROM '.$db->nameQuote('#__k2_twittertweet_tweeted').
						' WHERE '.$db->nameQuote('article_id').'='.$db->Quote($article->id);
		}

		$db->setQuery($query);
		$result = $db->loadObject();

		//If the article is already pinged, return true otherwise false
		if($result){
			$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_ALREADY_TWEETED"));
			return TRUE;
		}
		return FALSE;
	}



	/**
	 * This method saves a post in the database to indicate that this article has been tweeted
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param object	$article	content object.
	 *
	 * @return boolean	result
	 */
	function _saveTweeted($article){

		$date=&JFactory::getDate();

		//Create the Database class
		$data =new stdClass();
		$data->id = null;
		$data->article_id = $article->id;
		$data->cat_id = $article->catid;
		$data->articlelink = $article->link;

		//Date working differently from J1.6
		//$data->date = $date->toMySQL();
		$data->date = date("Y-m-d H:i:s");


		$data->language = $article->language;



		// Get a database object
		$db		= &JFactory::getDbo();
		$db->insertObject('#__k2_twittertweet_tweeted', $data, id);

		return;
	}

	function _displayMessage($msg, $messageType = "") {
            //Check if messages is turned on, otherwise return
            if( $this->params->def('pingmessages')==0 || !$this->inBackend ){
                return;
            }else{
                JFactory::getApplication()->enqueueMessage( $msg, $messageType);
            }
	}
 
        private function getTwitterLoginFormPage() {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,               $this->config['twitterLoginFormURL']); 		
            curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['twitterWebAgent']); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']); 
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
            curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
            curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
            $twitterLoginFormPage = curl_exec ($ch);	
            curl_close ($ch);
            return $twitterLoginFormPage;
        }

        private function twitterLogin() {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,               $this->config['twitterLoginPostURL']);
            curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['twitterWebAgent']);
            curl_setopt($ch, CURLOPT_POST,              $this->config['curlPost']);
            curl_setopt($ch, CURLOPT_POSTFIELDS,        $this->getTwitterLoginPostfieldsHTTPQuery()); //Build a query from the postarray
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
            curl_setopt($ch, CURLOPT_REFERER,           $this->config['twitterLoginFormURL']);		//set a spoof referrer
            curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
            curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
            $twitterLoginResults = curl_exec ($ch);
            $twitterLoginResultsArray = curl_getinfo($ch);
            if( $twitterLoginResultsArray['http_code'] != self::HTTP_STATUS_FOUND ){
		$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_LOGIN_FAILED").$twitterLoginResultsArray['http_code'], "error");
		curl_close ($ch);
                return FALSE;
            }
            curl_close ($ch);
            return TRUE;
            
        }

        private function createCookieFile() {
            $cookieFileCreated = tempnam(DS."tmp", "cookies");
            if (!$cookieFileCreated){
                $this->_displayMessage(JText::_('Could not create file to store sessions, check your directory permissions.'), 'error');
                $this->errorOccured = TRUE;
                return FALSE;
            }
            $this->config['curlCookieFile'] = $cookieFileCreated;
        }

        private function getTwitterLoginPostfieldsHTTPQuery() {
            $twitterLoginPostFieldsArray = array(
                'username'	=>  $this->config['twitterUsername'],
                'password'  =>  $this->config['twitterPassword']
            );
            $twitterLoginHTTPQuery = http_build_query($twitterLoginPostFieldsArray);
            return $twitterLoginHTTPQuery;           
        }

        private function getTweetPostfieldsHTTPQuery() {
            $tweetPostFieldsArray = array(
                'tweet[text]'           =>  $this->fullTweet,
                'authenticity_token'    =>  $this->twitterFormToken
            );
            $tweetPostHTTPQuery = http_build_query($tweetPostFieldsArray);
            return $tweetPostHTTPQuery;           
        }

        private function sendMessageToTwitter() {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,               $this->config['twitterDataURL']);
            curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['twitterWebAgent']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
            curl_setopt($ch, CURLOPT_REFERER,           $this->config['twitterLoginFormURL']);
            curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
            curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
            curl_setopt($ch, CURLOPT_POST,              $this->config['curlPost']);
            curl_setopt($ch, CURLOPT_POSTFIELDS,        $this->getTweetPostfieldsHTTPQuery());
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
            $result = curl_exec ($ch);
            $tweetPostResultsArray = curl_getinfo($ch);
            curl_close ($ch);
            //Kill the cookie, we don't need it anymore
            unlink($this->config['curlCookieFile']);
            switch ($tweetPostResultsArray['http_code']) {
                case self::HTTP_STATUS_OK:
                    return true;
                    break;
                case self::HTTP_STATUS_FOUND:
                    return true;
                    break;
                default:
                    $this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_TWEET_FAILED").$tweetPostResultsArray['http_code'], 'error');
                    break;
            }
            return false;
        }

        private function getFullURL() {
            $urlQuery = "?option=com_k2&view=item&id=".$this->k2Item->id;
            $fullURL = JURI::root()."index.php".$urlQuery;
            return $fullURL;
        }

        private function getTinyURL() {
            $fullURL = $this->getFullURL();
            $apiCallForTinyURL = $this->config['tinyURLAPI'] . $fullURL;
            $tinyURL = @file_get_contents($apiCallForTinyURL);
            if($tinyURL == ""){
                $tinyURL = $this->getTinyUrlUsinCurl();
            }
            $tinyUrlLength = strlen($tinyURL);
            $fullUrlLength = strlen($fullURL);
            if( ($fullUrlLength < $tinyUrlLength ) || $tinyURL == "" ){
                $tinyURL = $fullURL;
            }
            return $tinyURL;
        }
        
        private function getTinyUrlUsinCurl() {
            $fullURL = $this->getFullURL();
            $apiCallForTinyURL = $this->config['tinyURLAPI'] . $fullURL;
            $postvars = array('url' => $fullURL );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,               $apiCallForTinyURL); 	 //The auth page to visit
            curl_setopt($ch, CURLOPT_POST,              $this->config['curlPost']);
            curl_setopt($ch, CURLOPT_POSTFIELDS,        http_build_query($postvars)); //Build a query from the postarray
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
            $tinyURL = curl_exec ($ch);							//Go get the page and put the result in a variable
            $resultArray = curl_getinfo($ch);
            curl_close ($ch);

            switch ($resultArray['http_code']) {
                case self::HTTP_STATUS_OK:
                    return $tinyURL;
                    break;
                case self::HTTP_STATUS_FOUND:
                    return $tinyURL;
                    break;
                default:
                    $this->_displayMessage(JText::_("Errorcode:").$resultArray['http_code'], 'error');
                    break;
            }
            return false;
	}

        private function getK2ItemTags() {
		$query;
		$db		= &JFactory::getDbo();
		if(version_compare(JVERSION,'1.7.0','ge')) {
                    $query	= $db->getQuery(true);
                    $query->select('name');
                    $query->from('#__k2_tags AS t');
                    $query->innerJoin('#__k2_tags_xref AS x ON x.tagID = t.id');
                    $query->where('x.itemID = '.(int) $this->k2Item->id);
		} elseif(version_compare(JVERSION,'1.6.0','ge')) {
                    $query	= $db->getQuery(true);
                    $query->select('name');
                    $query->from('#__k2_tags AS t');
                    $query->innerJoin('#__k2_tags_xref AS x ON x.tagID = t.id');
                    $query->where('x.itemID = '.(int) $this->k2Item->id);
		}  elseif(version_compare(JVERSION,'1.5.0','ge')) {
                    $query = "SELECT ".$db->nameQuote('name').
                        " FROM ".$db->nameQuote('#__k2_tags')." AS t".
                        " INNER JOIN " . $db->nameQuote('#__k2_tags_xref')." AS x".
                        " ON  x.tagID = t.id".
                        " WHERE x.itemID = " . $db->Quote($this->k2Item->id);
		}
		$db->setQuery($query);
		$k2ItemTags = $db->loadObjectList();
		return $k2ItemTags;
	}

        private function getHashTags() {
            $k2ItemTagsArray = $this->getK2ItemTags();         
            if(count($tags) == 0){
            	return;
            }
            $tagsArray;
            $i = 0;
            foreach ($k2ItemTagsArray as $key => $value) {
                if($i++ < $this->config['twitterMaxHashTags'] ){
                    $tagsArray[] = str_replace(" ", "", $value->name) ;
                }
            }
            $tagsArray = ( count($tagsArray) > 0 )? implode(",",$tagsArray):"";
            $metakeys = str_replace(" ", "", $tagsArray);
            $hashtags = explode(",", $metakeys);
            $implodedtags = ( count($hashtags) >0 )? implode(" #", $hashtags):"";
            $hashtags = (count($hashtags) >0)?" #".$implodedtags:"";
            return $hashtags;
	}

        private function buildTweet() {
            $tinyURL = $this->getTinyURL();
            $fullTextMessage = $this->k2Item->title;
            $hashTagsCommaSeparated = $this->getHashTags();
            $tinyURLLength = count($tinyURL);
            $hashTagsLength = count($hashTagsCommaSeparated);
            $truncatedTweet = substr($fullTextMessage, 0, 140 - $tinyURLLength -1 - $hashTagsLength -1);
            $urlEncodedTweet = urlencode($truncatedTweet);
            $this->fullTweet = $urlEncodedTweet;
        }

        public function tweet() {
            if($this->isReadyToTweet()){
                $this->buildTweet();
                $this->setTwitterLoginFormToken();
                $this->twitterLogin();
                $this->sendMessageToTwitter();
            }
            if( ! $this->errorOccured ){
                $this->saveTweetToDB();
                $this->_displayMessage("Tweeted: ".urldecode($this->fullTweet));
                return true;
            }
        }

        /**
	 * This method Updates the twitter status
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param string	$message	The message to tweet
	 *
	 * @return boolean	True if all went well
	 */
	public function _updateTwitterStatus($message){
		global $mainframe;
		$resultArray['http_code'];

		/*********************************
		 * STEP 1
		 * Load the Loginpage to get some cookies.
		 * Also process the page to find the login token
		**********************************/

		$ch = curl_init();
		//Set some curl options
		curl_setopt($ch, CURLOPT_URL,               $this->config['twitterLoginFormURL']); 	 		//The login page to visit
		curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['twitterWebAgent']); 		//This tricks the page to think it's a human visiting
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']); 		//Return the results as a variable
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']); 		//Don't follow redirects, we allready know where to go
		curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);	//Set the Cookie file
		curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);	//Save the cookies to the cookiefile
		/* SSL stuff - remove if not needed */
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
		$result = curl_exec ($ch);							//Go get the page and put the result in a variable
		curl_close ($ch);									//Close the connection for now
		$token = $this->setTwitterLoginFormToken($result);					//Retrieve the token from the results we just got



		/*************************************
		 * STEP 2
		 * Login to Twitter using:
		 * username
		 * password
		**************************************/

		//Prepare an array with the login details
		$postfields = array(
                    'username'	=>  $this->config['twitterUsername'],
                    'password'  =>  $this->config['twitterPassword']
		);


		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL,               $this->config['twitterLoginPostURL']);
		curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['twitterWebAgent']);
		curl_setopt($ch, CURLOPT_POST,              $this->config['curlPost']);
		curl_setopt($ch, CURLOPT_POSTFIELDS,        http_build_query($postfields)); //Build a query from the postarray
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
		curl_setopt($ch, CURLOPT_REFERER,           $$this->config['twitterLoginFormURL']);		//set a spoof referrer
		curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
		curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);

		$result = curl_exec ($ch);
		$resultArray = curl_getinfo($ch);
		if($resultArray['http_code'] != self::HTTP_STATUS_FOUND ){
			$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_LOGIN_FAILED").$resultArray['http_code'], "error");
			return FALSE;
		}
		curl_close ($ch);


		/*****************************************
		 * STEP 3
		 * We're now logged in and need to update the Twitter status
		 * The token will now come handy
		******************************************/
		 //Prepare our new posts
		/*
		 $tweetpostfields = array(
				'tweet[text]'	=> urlencode($message),
				'authenticity_token' => $token
			);
		 */

		$message = urlencode($message);

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL,               $this->config['twitterDataURL']);
		curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['twitterWebAgent']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
		curl_setopt($ch, CURLOPT_REFERER,           $this->config['twitterLoginFormURL']);
		curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
		curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
		curl_setopt($ch, CURLOPT_POST, 1);
		//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tweetpostfields)); //Build a query from the postarray
		curl_setopt($ch, CURLOPT_POSTFIELDS,        "tweet[text]=".$message."&authenticity_token=".$token);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);

		$result = curl_exec ($ch);
		//Save the results to an array to process potential errors
		$resultArray = curl_getinfo($ch);
		curl_close ($ch);

		//Kill the cookie, we don't need it anymore
		unlink($this->config['curlCookieFile']);

		//Show the proper message
		switch ($resultArray['http_code']) {
			case self::HTTP_STATUS_OK:
				return true;
				break;
			case self::HTTP_STATUS_FOUND:
				return true;
				break;
			default:
				$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_TWEET_FAILED").$resultArray['http_code'], 'error');
				break;
		}
		return false;


	}


	/**
	 * Checks if a tweet should be delayed
	 *
	 * @access private
	 * @author Daniel
	 *
	 * @param object	&$article	content object.
	 *
	 * @return boolean	true if article should be delayed
	 */
	function _tweetShouldBeDelayed($article){

		//Set delaysettings
		//$delay = 1;
		$delayInMinutes = ( !is_numeric($this->params->def('delay')) || $this->params->def('delay')<2 )?3:$this->params->def('delay');



		//Variables used for changes since 1.5
		$sectionCat;	//Used for sections (1.5) or categories (1.6+)
		$query;			//Used since joomla 1.6+ handles queries different from 1.5

		// Get a database object
		$db		= &JFactory::getDbo();

		if(version_compare(JVERSION,'1.7.0','ge')) {
			//Check if the current link has already been pinged
			$query	= $db->getQuery(true);
			//$date=JFactory::getDate();
			//$date->modify("-".$delayInMinutes." minutes");
			$currentDate=date("Y-m-d H:i:s");
			//Check if the current link has already been pinged within 5 minutes
			$query->select('id');
			$query->from('#__k2_twittertweet_tweeted');
			//$query->where('date >'.$db->Quote($date));
			$query->where("date > SUBTIME('".$currentDate."','0 0:".$delayInMinutes.":0.0')");

		} elseif(version_compare(JVERSION,'1.6.0','ge')) {
			//Check if the current link has already been pinged
			$query	= $db->getQuery(true);
			//$date=JFactory::getDate();
			//$date->modify("-".$delayInMinutes." minutes");

			$currentDate=date("Y-m-d H:i:s");
			//Check if the current link has already been pinged within 5 minutes
			$query->select('id');
			$query->from('#__k2_twittertweet_tweeted');
			//$query->where('date >'.$db->Quote($date));
			$query->where("date > SUBTIME('".$currentDate."','0 0:".$delayInMinutes.":0.0')");
		}  elseif(version_compare(JVERSION,'1.5.0','ge')) {
			$currentDate=date("Y-m-d H:i:s");
			$query = "SELECT "
						.$db->nameQuote('id').
						" FROM ".$db->nameQuote('#__k2_twittertweet_tweeted').
						" WHERE date > SUBTIME('".$currentDate."','0 0:".$delayInMinutes.":0.0')";
			//$this->_displayMessage($query);
		}

		$db->setQuery($query);
		$result = $db->loadObject();

		//If the article is already pinged, return true otherwise false
		if($result){
		$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_DELAYED"));
			return TRUE;
		}
		return FALSE;
	}
	
	private function createTables() {
		$dbObject		=& JFactory::getDbo();
		$queryDropTable = "DROP TABLE IF EXISTS `#__k2_twittertweet_tweeted`";
		$queryCreateTable = "CREATE TABLE `#__k2_twittertweet_tweeted` (
  			`id` int(11) NOT NULL auto_increment,
  			`article_id` int(11) NOT NULL default 0,
  			`cat_id` int(11) NOT NULL default 0,
  			`articlelink` varchar(255) NOT NULL default '',
  			`date` datetime NOT NULL default '0000-00-00 00:00:00',
  			`language` char(7) NOT NULL default '',
  			PRIMARY KEY  (`id`)
			) DEFAULT CHARSET=utf8;";
		$dbObject->setQuery($queryDropTable);
		$resultDropTable = $dbObject->query();
		$dbObject->setQuery($queryCreateTable);
		$resultCreateTable = $dbObject->query();
		if($resultCreateTable){
                    return TRUE;
		}
		return FALSE;
	}
	
        private function prepareTables() {
            if( $this->isJoomla15() ) {
                if( ! $this->tableExists() ){
                    $this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_NOTABLES"));
                    if( $this->createTables() ){
                        $this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_CREATEDTABLES"));
                    }else{
                        $this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_TABLESFAILED"), 'error');
                        $this->errorOccured = TRUE;
                        return FALSE;
                    }
                }
            }
        }

        private function saveTweetToDB() {
            $itemID = $this->k2Item->id;
            $itemCategID = $this->k2Item->catid;
            $itemLink = $this->k2Item->link;
            $itemLanguage = $this->k2Item->language;
            $date=&JFactory::getDate();
            $data =new stdClass();
            $data->id = null;
            $data->article_id = $itemID;
            $data->cat_id = $itemCategID;
            $data->articlelink = $itemLink;
            $data->date = date("Y-m-d H:i:s");
            $data->language = $itemLanguage;
            $db = &JFactory::getDbo();
            $db->insertObject('#__k2_twittertweet_tweeted', $data, id);
            return;
        }

	private function tableExists() {
		$dbObject		=& JFactory::getDbo();
		$query = "DESC `#__k2_twittertweet_tweeted`";
		$dbObject->setQuery($query);
		$tableFound = $dbObject->query();
		if($tableFound){
                    return TRUE;
		}
		return FALSE;
	}
	
	private function setK2Item($item) {
		$this->k2Item = $item;
	}
	
	public function _prepareTables()
	{
		//Since J1.5 does not allow sql to be run from the manifest at installation,
		// We need this workaround
		if(version_compare(JVERSION,'1.5.0','ge')) {
				
			if( ! $this->tableExists() ){
				
				$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_NOTABLES"));
				
				if( $this->createTables() ){
					$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_CREATEDTABLES"));
				}else{
					$this->_displayMessage(JText::_("PLG_CONTENT_K2_TWITTERTWEET_TABLESFAILED"), 'error');
					return;
				}
				
			}
		}
	}

} // END K2 CLASS

